package com.zttek.photosShareProject.modules.web.login;

import com.google.code.kaptcha.Constants;
import com.zttek.photosShareProject.common.base.MyBaseController;
import com.zttek.photosShareProject.common.myException.DBException;
import com.zttek.photosShareProject.common.result.CurrentUserResult;
import com.zttek.photosShareProject.common.utils.CryptographyUtil;
import com.zttek.photosShareProject.common.utils.JavaMailUtil;
import com.zttek.photosShareProject.common.utils.OSSClientUtil;
import com.zttek.photosShareProject.common.utils.PasswordUtil;
import com.zttek.photosShareProject.modules.model.Admin;
import com.zttek.photosShareProject.modules.model.Image;
import com.zttek.photosShareProject.modules.service.login.IUserService;
import com.zttek.photosShareProject.modules.service.login.impl.UserServiceImpl;
import com.zttek.photosShareProject.modules.model.User;
import com.zttek.photosShareProject.modules.service.manager.IAdminService;
import com.zttek.photosShareProject.modules.service.share.IImageService;
import com.zttek.photosShareProject.modules.service.share.impl.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 13296 on 2017/8/11.
 */
@Controller
public class LoginController extends MyBaseController{
    @Autowired
    private IUserService userService;
    @Autowired
    private IImageService imageService;
    @Autowired
    private IAdminService adminService;

    @RequestMapping(value = {"login"},method = RequestMethod.GET)
    public String loginView(String loginMessage,String findPasswordMessage,Model model) {
        model.addAttribute("loginMessage",loginMessage);
        model.addAttribute("findPasswordMessage",findPasswordMessage);
        return null;
    }

    /**
     * 用户登录POST
     * @param password
     * @param account
     * @param model
     * @param verifyCode
     * @param request
     * @return
     */
    @RequestMapping(value = {"login"},method = RequestMethod.POST)
    public String login(String password, String account, Model model, String verifyCode, HttpServletRequest request, HttpServletResponse response) {
        String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);        //获取生成的验证码
        System.out.println(verifyCode + "," + code);
        User user =null;
        try {
            /*验证码验证*/
            if(!verifyCode.equals(code)) {
                throw new DBException("验证码错误！");
            }
            System.out.println("验证通过 ");
            /*用户验证 */
            user = userService.selectUserByAccount(account);
            if(!PasswordUtil.verify(password,user.getPassword())){
                throw new DBException("密码错误！");
            }
            /*创建当前用户值对象*/
            CurrentUserResult cu = new CurrentUserResult();
            cu.setId(user.getId());
            cu.setAccount(user.getAccount());
            cu.setUsername(user.getUsername());
            cu.setMail(user.getEmail());
            cu.setIsShare(user.getIsShare());
            Image image = imageService.selectImageById(user.getPortraitId());
            cu.setPortraitPath(image.getPath());
            cu.setPortraitThumbPath(image.getThumbPath());
            HttpSession session = request.getSession();
            session.setAttribute("currentUser",cu);
        } catch (Exception e) {
            model.addAttribute("loginMessage",e.getMessage());
            System.out.println("loginMessage"+e.getMessage());
            e.printStackTrace();
            return "redirect:login";
//            return null;
        }
        return "redirect:share/index";
    }

    /**
     * 用户注册GET
     * @param request
     * @return
     */
    @RequestMapping(value = "user/register",method = RequestMethod.GET)
    public String register(HttpServletRequest request) {
        return null;
    }

    /**
     * 用户注册POST
     * @param account
     * @param password
     * @param model
     * @param email
     * @param request
     * @return
     */
    @RequestMapping(value = "user/register",method = RequestMethod.POST)
    public String register(String account,String password,Model model,String email,HttpServletRequest request){
        Date date = new Date();
        User user = new User();
        user.setCreateTime(date);
        //user.setUpdateTime(date);
        user.setAccount(account);
        //密码加密
        password = PasswordUtil.generate(password);
        user.setPassword(password);
        user.setEmail(email);
        try {
            List<User> list = userService.selectAllUser();
            for(User u:list){
                if(u.getAccount().equals(account)){
                    throw new DBException("该账号已存在");
                }
            }
            userService.insertUser(user);
        } catch (Exception e) {
            model.addAttribute("registerMessage",e.getMessage());
            e.printStackTrace();
            return null;
        }
        System.out.println("注册成功！");
        return "redirect:/login";
    }

    @RequestMapping(value = "user/updatepassword",method = RequestMethod.GET)
    public String uodatePasswordView(String password,String account,Model model,boolean isAdmin){
        return null;
    }

    @RequestMapping(value = "user/updatepassword",method = RequestMethod.POST)
    public String uodatePassword(String oldPassword,String newPassword,String account,boolean isAdmin,Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user =null;
        Admin admin = null;
        try {
            newPassword = PasswordUtil.generate(newPassword);
            if(!isAdmin){
                user = (User)session.getAttribute("currentUser");
//                System.out.println("id:"+user.getId());
                //user = userService.selectUserByAccount(account);
                if(!PasswordUtil.verify(oldPassword,user.getPassword())) {
                    throw new DBException("旧密码不正确");
                }
                user.setPassword(newPassword);
                userService.updateUser(user);
            }else {
                admin = (Admin) session.getAttribute("currentAdmin");
                if (!PasswordUtil.verify(oldPassword, admin.getPassword())) {
                    throw new DBException("旧密码不正确");
                }
                admin.setPassword(newPassword);
                adminService.updateAdmin(admin);
            }
            System.out.println("更新成功！");
        } catch (Exception e) {
            model.addAttribute("updatepasswordMessage",e.getMessage());
            e.printStackTrace();
            return null;
        }
        System.out.println("修改密码成功！");
        model.addAttribute("updatePasswordMessage","修改成功");
        if(!isAdmin){
            return "redirect:/login";
        }else{
            return "redirect:/adminLogin";
        }

    }


    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        //redirect:/login
        return "redirect:/login";
    }

    /**
     * 跳转登录主页
     * @param model
     * @return
     */
    @RequestMapping(value = "share/index",method = RequestMethod.GET)
    public String indexView(Model model,HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session.getAttribute("currentUser")==null){
            return "redirect:/login";
        }
        return null;
    }

    @RequestMapping(value = "share/index",method = RequestMethod.POST)
    public String index(Model model) {
        return null;
    }

    /**
     * 通过邮箱找回密码
     * @param model
     * @return
     */
    @RequestMapping(value = "user/findPassword",method = RequestMethod.GET)
    public String findPasswordView(Model model,boolean isAdmin) {
        model.addAttribute("isAdmin",isAdmin);
        return null;
    }

    @RequestMapping(value = "user/findPassword",method = RequestMethod.POST)
    public String findPassword(String account,String email,String verifyCode,boolean isAdmin,Model model,HttpServletRequest request) {
        String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);        //获取生成的验证码
        System.out.println(verifyCode + "," + code);
        User user =null;
        Admin admin = null;
        try {
            /*验证码验证*/
            if(!verifyCode.equals(code)) {
                throw new DBException("验证码错误！");
            }
            System.out.println("验证通过 ");
            String basePath = getBasePath(request);
            System.out.println("basePath:"+basePath);
            System.out.println("isAdmin:"+isAdmin);
            if(!isAdmin){
                  /*用户验证 */
                user = userService.selectUserByAccount(account);
                if(!user.getEmail().equals(email)){
                    throw new DBException("该账号邮箱错误！");
                }
                 /*添加凭证*/
                String resetPasswordToken = CryptographyUtil.encodeResetPasswordToken(user.getId(),isAdmin);
                System.out.println("凭证："+resetPasswordToken);
                user.setResetPasswordToken(resetPasswordToken);
                userService.updateUser(user);
                  /*发送邮箱*/
                JavaMailUtil.sentEmail(resetPasswordToken,user.getEmail(),basePath);
            }else{
                System.out.println("这里是管理员重置密码！");
                admin = adminService.selectAdminByAccount(account);
                if(!admin.getEmail().equals(email)){
                    throw new DBException("该账号邮箱错误！");
                }
                  /*添加凭证*/
                String resetPasswordToken = CryptographyUtil.encodeResetPasswordToken(admin.getId().longValue(),isAdmin);
                admin.setResetPasswordToken(resetPasswordToken);
                adminService.updateAdmin(admin);
                  /*发送邮箱*/
                JavaMailUtil.sentEmail(resetPasswordToken,admin.getEmail(),basePath);
            }

        } catch (Exception e) {
            model.addAttribute("findPasswordMessage",e.getMessage());
            model.addAttribute("account",account);
            model.addAttribute("email",email);
            model.addAttribute("isAdmin",isAdmin);
            e.printStackTrace();
            return null;
        }

        model.addAttribute("findPasswordMessage","success");
        if(!isAdmin){
            return "redirect:/login";
        }else {
            return "redirect:/adminLogin";
        }
    }

    /**
     * 通过邮箱重置密码
     * @param model
     * @return
     */
    @RequestMapping(value = "user/resetPassword",method = RequestMethod.GET)
    public String resetPasswordView(String resetPasswordToken,Model model){
        model.addAttribute("resetPasswordToken",resetPasswordToken);
        return null;
    }

    @RequestMapping(value = "user/resetPassword",method = RequestMethod.POST)
    public String resetPassword(String newPassword,String resetPasswordToken,Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user =null;
        Admin admin =null;
        try {
            System.out.println("token:"+resetPasswordToken);
            ArrayList list = CryptographyUtil.decodeResetPasswordToken(resetPasswordToken);
            Long id = (Long) list.get(0);
            Long tokenDateTime = (Long)list.get(1);
            boolean isAdmin = (boolean)list.get(2);

            if(!isAdmin){
                user = userService.selectUserById(id);
                if(!resetPasswordToken.equals(user.getResetPasswordToken())){
                    throw new DBException("重置密码凭证错误！");
                }
            }else {
                admin = adminService.selectAdminByID(id.intValue());
                if(!resetPasswordToken.equals(admin.getResetPasswordToken())){
                    throw new DBException("重置密码凭证错误！");
                }
            }
            Long currentDateTime = new Date(new Date().getTime()).getTime();
            //3600 * 1000 * 2 两小时
            if(currentDateTime-tokenDateTime>3660 * 1000*2){
                throw new DBException("重置密码凭证已过期！");
            }else{
                System.out.println("curentDateTime-tokenDateTime="+(currentDateTime-tokenDateTime));
            }
            newPassword = PasswordUtil.generate(newPassword);
            if(!isAdmin){
                user.setPassword(newPassword);
                userService.updateUser(user);
            }else {
                admin.setPassword(newPassword);
                adminService.updateAdmin(admin);
            }
            System.out.println("重置密码成功！");
        } catch (Exception e) {
            model.addAttribute("resetPasswordMessage",e.getMessage());
            e.printStackTrace();
            return null;
        }
        System.out.println("通过邮箱重置密码成功！");
        return "redirect:/login";
    }

}
